package com.xierong.remoteplayerlauncher;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xierong.remoteplayerlauncher.model.PlayListItem;
import com.xierong.remoteplayerlauncher.utils.PlayerManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

public class FileCopyActivity extends Activity {
    private TextView counterText = null;
    private ProgressBar progressBar = null;
    private String configFilePath = null;
    private int totalFiles = 0;
    private int fileCopied = 0;
    private long totalSize = 0;
    private long copiedSize = 0;
    private Thread copyFileThread;
    private Runnable run = null;
    private FileInputStream fileInputStream = null;
    private FileOutputStream fileOutputStream = null;
    private FileChannel fileChannelOutput = null;
    private FileChannel fileChannelInput = null;
    private BufferedInputStream inbuff = null;
    private BufferedOutputStream outbuff = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_copyfile);
        counterText = findViewById(R.id.progress_count_text);
        progressBar = findViewById(R.id.progressBar);
        Intent intent = getIntent();
        configFilePath = intent.getExtras().getString("path");
        if (configFilePath != null) {
            loadExternalConfig(configFilePath);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                int progress = msg.getData().getInt("progress");
                progressBar.setProgress(progress);
            } else if (msg.what == 1) {
                fileCopied++;
                counterText.setText(String.format("正在拷贝第%d/%d个文件", fileCopied, totalFiles));
            } else if (msg.what == 3) {
                Log.d(PlayerManager.TAG, "开始重启应用");
                Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
                intent.putExtra("REBOOT", "reboot");
                PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
                AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
    };
    private void loadExternalConfig(String path) {
        ArrayList<PlayListItem> list = PlayerManager.getInstance().pathToPlaylist(path);
        ArrayList<PlayListItem> copyList = new ArrayList<>();
        if (list != null) {
            for(PlayListItem item: list) {
                if (item.getPath() == "" || item.getPath() == null) {
                    continue;
                } else {
                    File currentFile = new File(item.getPath());
                    if (currentFile.exists()) {
                        totalSize += currentFile.length();
                        String fileName = currentFile.getName();
                        item.setCopyTargetPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + fileName);
                        copyList.add(item);
                    } else {
                        continue;
                    }
                }
            }
            Log.d(PlayerManager.TAG, "需要拷贝的文件个数：" + copyList.size());
            if (copyList.size()>0) {
                deleteOldFiles();
                copyFiles(copyList);
            } else {
                Toast.makeText(getApplicationContext(), "播放列表配置文件中没有可以进行复制的文件", Toast.LENGTH_SHORT).show();
                this.finish();
            }
        } else {
            Toast.makeText(getApplicationContext(), "播放列表为空或者配置错误", Toast.LENGTH_SHORT).show();
            this.finish();
        }
    }
    private void deleteOldFiles() {
        String oldPlayListPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "playlist.xml";
        File oldFile = new File(oldPlayListPath);
        if (oldFile.exists()) {
            ArrayList<PlayListItem> oldList = PlayerManager.getInstance().pathToPlaylist(oldPlayListPath);
            for(PlayListItem item: oldList) {
                File file = new File(item.getPath());
                if (file.exists()) {
                    file.delete();
                }
            }
            oldFile.delete();
        }
    }
    private void copyFiles(ArrayList<PlayListItem> list) {
        Log.d(PlayerManager.TAG, "开始进行文件处理");
        fileCopied = 0;
        totalFiles = list.size();
        counterText.setText(String.format("正在拷贝第%d/%d个文件", fileCopied, totalFiles));
        run = new Runnable() {
            @Override
            public void run() {
                for(PlayListItem item : list) {
                    copyFile(item.getPath(), item.getCopyTargetPath());
                }
                copyFile(configFilePath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "playlist.xml");
                Log.d(PlayerManager.TAG, "文件复制完成");
                Message message = handler.obtainMessage(3);
                handler.sendMessage(message);
            }
        };
        copyFileThread = new Thread(run);
        copyFileThread.start();
    }
    private synchronized void copyFile(String from, String target) {
        try {
            File fromFile = new File(from);
            File targetFile = new File(target);
            fileInputStream = new FileInputStream(fromFile);
            fileOutputStream = new FileOutputStream(targetFile);
            fileChannelOutput = fileOutputStream.getChannel();
            fileChannelInput = fileInputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            long transferSize = 0;
            long size = fromFile.length();
            int tempP = 0;
            int progress = 0;
            while(fileChannelInput.read(buffer) != -1) {
                buffer.flip();
                transferSize += fileChannelOutput.write(buffer);
                copiedSize += transferSize;
                progress = (int)(transferSize * 100 / size);
                if (progress > tempP) {
                    tempP = progress;
                    Message message = handler.obtainMessage(0);
                    Bundle bundle = new Bundle();
                    bundle.putInt("progress", progress);
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
                buffer.clear();
            }
            Message msg = handler.obtainMessage(1);
            handler.sendMessage(msg);
            fileOutputStream.flush();
            fileOutputStream.close();
            fileInputStream.close();
            fileChannelOutput.close();
            fileChannelInput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
